package com.example.nacosclientrabbit.repository;

import com.alibaba.fastjson.JSON;
import com.example.nacosclientrabbit.entity.Message;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Slf4j
@Service
public class SendRepositoryImpl implements SendRepository {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Object send(Message message) {
        rabbitTemplate.setConfirmCallback(this);
        CorrelationData dataId = new CorrelationData(UUID.randomUUID().toString());
        //判断是否同步
        if (message.isSync()){
            //发送同步消息
            Object o = rabbitTemplate.convertSendAndReceive(message.getExchange(), message.getRoutingKey(), JSON.toJSONString(message.getBody()), dataId);
            log.info("return sync obj:{}", o);
            return o;
        }else {
            //发送异步消息
            rabbitTemplate.convertAndSend(message.getExchange(), message.getRoutingKey(), JSON.toJSONString(message.getBody()), dataId);
            return null;
        }
    }


    /**
     * 在生产端判断消息是否发送成功
     * @param correlationData
     * @param confirm
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean confirm, String cause) {
        if (confirm){
            log.info("send success");
        }else {
            log.info("send fail");
        }
    }
}
